# -*- coding: utf-8 -*-
import datetime
import threading
import json
from functools import wraps

def semaphore(function):
    @wraps(function)
    def wrapper(self, *args, **kwargs):
        self.semaphore.acquire()
        res = function(self, *args, **kwargs)
        self.semaphore.release()
        return res

    return wrapper

class operation_coordinator(threading.Thread):
    def __init__(self, cloudmqtt):
        threading.Thread.__init__(self)
        self.semaphore = threading.Semaphore()

        self._device_ctl_list = dict()  # 设备列表
        self._cloudmqtt = cloudmqtt
        self._status_timer = threading.Timer(5, self.fun_status_timer)
        self._status_timer.start()
        self._report_cloud_timer = threading.Timer(5, self.fun_report_cloud_timer)
        self._report_cloud_timer.start()

    @semaphore
    def add_new_devicectl(self, dev_id, device_ctl):
        self._device_ctl_list[dev_id] = device_ctl
        self._cloudmqtt.subscribe(dev_id)

    @semaphore
    def remove_devicectl(self, dev_id):
        if dev_id in self._device_ctl_list:
            del self._device_ctl_list[dev_id]

    def run(self):
        while True:
            # 数据处理，预测优化...
            pass

    @semaphore
    def fun_status_timer(self):
        now_datetime = datetime.datetime.now()
        for dev_id in self._device_ctl_list:
            if (now_datetime - self._device_ctl_list[dev_id]._last_recv_datetime).seconds > 10:
                self._device_ctl_list[dev_id]._devicestatus = -1  #表示设备离线
            else:
                self._device_ctl_list[dev_id]._devicestatus = 1  # 表示在线
        self._status_timer = threading.Timer(5, self.fun_status_timer)
        self._status_timer.start()

    @semaphore
    def fun_report_cloud_timer(self):
        now_datetime = datetime.datetime.now()
        print ("\n\n**************************************")
        for dev_id in self._device_ctl_list:
            self._cloudmqtt.push_to_cloud("device_status",json.dumps({"devid":dev_id,"devstatus":1}))
            print ("设备%s --- 通信状态：%s, 设备状态%s"%(dev_id.encode("utf-8"), "在线" if self._device_ctl_list[dev_id]._devicestatus==1 else "离线" ,self._device_ctl_list[dev_id].get_dev_status()))
        print ("**************************************\n\n")
        self._report_cloud_timer = threading.Timer(5, self.fun_report_cloud_timer)
        self._report_cloud_timer.start()

